/**
 * Copyright (c) 2017-2024 Nop Platform. All rights reserved.
 * Author: canonical_entropy@163.com
 * Blog:   https://www.zhihu.com/people/canonical-entropy
 * Gitee:  https://gitee.com/canonical-entropy/nop-entropy
 * Github: https://github.com/entropy-cloud/nop-entropy
 */
package com.gitee.wsl.struct.table.tree

import com.gitee.wsl.struct.tree.builder.ChildDeclaration

/**
 * 通过expander展开每层的单元格，构建树形结构
 *
 * @param <T>
</T> */
class TreeCellBuilder<T : Any> {

    fun buildRootCells(cells: List<T>, childPos: TreeCellChildPosition): List<TreeCell> {
        val ret: MutableList<TreeCell> = ArrayList<TreeCell>(cells.size)
        for (cell in cells) {
            val box = TreeCell(cell, childPos)
            box.treeLevel = 0
            ret.add(box)
        }
        return ret
    }

    fun buildTreeCells(
        expander: ITreeCellExpander<T>, cells: List<T>,
        childPos: TreeCellChildPosition
    ): List<TreeCell> {
        val list = buildRootCells(cells, childPos)
        expandTreeCells(expander, list)
        return list
    }

    fun expandTreeCells(expander: ITreeCellExpander<T>, cells: List<TreeCell>) {
        for (cell in cells) {
            val children = expander.buildChildren(cell)
            if (children != null) {
                val childLevel: Int = cell.treeLevel + 1
                //cell.children = children as MutableList<TreeNode>
                cell.clear()
                for (child in children) {
                    cell.addChild(child)
                    child.parent = cell
                    child.treeLevel = childLevel
                }

                expandTreeCells(expander, children)
            }
        }
    }
}


inline fun treeCell(
    root: Any,
    childDeclaration: ChildDeclaration<Any?, TreeCell>,
): TreeCell {
    val treeNode = TreeCell(root,TreeCellChildPosition.hor)
    treeNode.childDeclaration()
    return treeNode
}